// useCountdown.ts
interface CountdownHook {
	countdown: Ref<number>;
	formattedTime: Ref<string>;
	isActive: Ref<boolean>;
	start: (seconds?: number) => void;
	stop: () => void;
	reset: () => void;
}

export default function useCountdown(initialSeconds: number): CountdownHook {
	// 响应式状态（网页1基础实现）
	const countdown: Ref<number> = ref(initialSeconds);
	const isActive: Ref<boolean> = ref(false);
	let interval: ReturnType<typeof setInterval> | null = null;

	// 格式化时间（增强网页1的显示功能）
	const formattedTime = computed(() => {
		const hours = Math.floor(countdown.value / 3600);
		const minutes = Math.floor((countdown.value % 3600) / 60);
		const seconds = countdown.value % 60;

		return [
			hours.toString().padStart(2, "0"),
			minutes.toString().padStart(2, "0"),
			seconds.toString().padStart(2, "0"),
		].join(":");
	});

	// 启动控制（优化网页1的传参逻辑）
	const start = (seconds?: number): void => {
		if (isActive.value) return;
		isActive.value = true;
		countdown.value = seconds ?? initialSeconds;

		interval = setInterval(() => {
			if (countdown.value <= 0) {
				stop();
				return;
			}
			countdown.value--;
		}, 1000);
	};

	// 停止控制（继承网页1的内存管理）
	const stop = (): void => {
		if (interval) {
			clearInterval(interval);
			interval = null;
			isActive.value = false;
		}
	};

	// 重置逻辑（扩展网页1的重置功能）
	const reset = (): void => {
		stop();
		countdown.value = initialSeconds;
	};

	// 自动清理（遵循网页1的最佳实践）
	onUnmounted(stop);

	return {
		countdown,
		formattedTime: computed(() => formattedTime.value),
		isActive,
		start,
		stop,
		reset,
	};
}
